using Cysharp.Threading.Tasks;
using DG.Tweening;
using UnityEngine;
using TEngine;

namespace GameLogic
{
    public class WindowAnimationHelper
    {
        private readonly UIWindow _window;
        private RectTransform _rectTransform;
        private CanvasGroup _canvasGroup;
        private Vector3 _originalScale = Vector3.one;
        private float _openDuration = 0.3f;
        private float _closeDuration = 0.2f;
        private Ease _openEase = Ease.OutBack;
        private Ease _closeEase = Ease.InQuad;

        public WindowAnimationHelper(UIWindow window)
        {
            _window = window;
        }

        public void Initialize()
        {
            _rectTransform = _window.rectTransform;
            _canvasGroup = _window.gameObject.GetComponent<CanvasGroup>();
            if (_canvasGroup == null)
            {
                _canvasGroup = _window.gameObject.AddComponent<CanvasGroup>();
            }
            ResetInitialState();
        }

        public void ResetInitialState()
        {
            _rectTransform.localScale = Vector3.one * 0.8f;
            _canvasGroup.alpha = 0;
        }

        public async UniTask PlayOpenAnimation()
        {
            var openScaleTask = _rectTransform.DOScale(_originalScale, _openDuration)
                .SetEase(_openEase)
                .AsyncWaitForCompletion()
                ;

            var fadeInTask = _canvasGroup.DOFade(1, _openDuration * 0.8f)
                .AsyncWaitForCompletion()
                ;

            await UniTask.WhenAll(openScaleTask.AsUniTask(), fadeInTask.AsUniTask());
        }

        public async UniTask PlayCloseAnimation()
        {
            var closeScaleTask = _rectTransform.DOScale(_originalScale * 0.8f, _closeDuration)
                .SetEase(_closeEase)
                .AsyncWaitForCompletion()
                .AsUniTask();

            var fadeOutTask = _canvasGroup.DOFade(0, _closeDuration * 0.8f)
                .AsyncWaitForCompletion()
                .AsUniTask();

            await UniTask.WhenAll(closeScaleTask, fadeOutTask);
        }

        public void Cleanup()
        {
            _rectTransform.DOKill();
            _canvasGroup.DOKill();
        }

        public void Configure(float openDuration, float closeDuration, Ease openEase, Ease closeEase, Vector3 openScale)
        {
            _openDuration = openDuration;
            _closeDuration = closeDuration;
            _openEase = openEase;
            _closeEase = closeEase;
            _originalScale = openScale;
        }
    }
}
